package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
       Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对

        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5Password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {
        /**
         * 1. 校验用户是否已存在
         */
/*        Employee employee = employeeMapper.getByUsername(employeeDTO.getUsername());
        if(employee != null) {
            throw new UsernameExistException(MessageConstant.USERNAME_EXIST);
        }*/

//        System.out.println("当前线程的id为："+Thread.currentThread().getId());
        Pattern p1 = Pattern.compile("\\d{18}|\\d{17}X");
        if(!p1.matcher(employeeDTO.getIdNumber()).matches()){
            throw new IdcardErrorException(MessageConstant.IDCARD_FORMAT_ERROR);
        }

        if(!employeeDTO.getPhone().matches("\\d{11}")){
            throw new PhoneErrorException(MessageConstant.PHONE_Error);
        }

        /**
         *     private Long id;
         *
         *     private String username;
         *
         *     private String name;
         *
         *     private String phone;
         *
         *     private String sex;
         *
         *     private String idNumber;
         */
        Employee employee1 = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee1);
//        employee1.setStatus(StatusConstant.ENABLE);
        employee1.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
//        employee1.setCreateTime(LocalDateTime.now());
//        employee1.setUpdateTime(LocalDateTime.now());

        //TODO 后期需修改为当前用户
//        Long id = BaseContext.getCurrentId();
//        employee1.setCreateUser(id);
//        employee1.setUpdateUser(id);

        employeeMapper.insert(employee1);

    }

    /**
     * 实现员工分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> page = (Page<Employee>)employeeMapper.pageQuery(employeePageQueryDTO);
        long total = page.getTotal();
        List<Employee>employeeList = page.getResult();
        PageResult pageResult = new PageResult(total,employeeList);
        return pageResult;
    }

    /**
     * 启用禁用员工账号
     * @param id
     * @param status
     */
    public void startOrStop(Long id, Integer status) {
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .updateUser(BaseContext.getCurrentId())
                .updateTime(LocalDateTime.now()).build();
        employeeMapper.update(employee);
    }

    /**
     * 员工信息页面回显
     * @param id
     * @return
     */
    public Employee getEmployeeById(Long id) {
        Employee employee = employeeMapper.getById(id);
        employee.setPassword("****");
        return employee;
    }

    /**
     * 修改员工信息
     * @param employeeDTO
     */
    public void update(EmployeeDTO employeeDTO) {
        Employee employee1 = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee1);
//        employee1.setUpdateTime(LocalDateTime.now());
//        employee1.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee1);
    }

    /**
     * 修改密码
     * @param passwordEditDTO
     * @return
     */
    public void editPassword(PasswordEditDTO passwordEditDTO){
        Long id = BaseContext.getCurrentId();
        Employee emp = employeeMapper.getById(id);
        if(emp == null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if(!emp.getPassword().equals(DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes()))){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        Employee employee = new Employee();
        employee.setId(id);
        employee.setPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
        employeeMapper.update(employee);
    }
}
